import type { Router } from 'vue-router'
import { useAuthStoreWithout } from '@/store/modules/auth'
import { useChatStore } from '@/store'
import {fetchVerify} from "@/api";
import {ref} from "vue";
import {router} from "@/router/index";

interface Token {
	token: string;
	refreshToken: string;
	expiresIn: number;
}

interface Login {
	tel: string;
	password: string;
	checked: false;
	loginType: number;
	tenantId:0;
}
const loginValue = ref<Login>({
	tel: "",
	password: "",
	checked: false,
	loginType: 3,
	tenantId:0
});
function getUrlParams(url) {
	const reg = /(\w+)=([^&]+)/g;
	const params = {};
	let match;

	while ((match = reg.exec(url)) !== null) {
		params[match[1]] = match[2];
	}

	return params;
}
export function setupPageGuard(router: Router) {

  router.beforeEach(async (to, from, next) => {
    const chatStore = useChatStore();
    const authStore = useAuthStoreWithout();
    if (to.path == '/login') {
      authStore.removeToken();
      next();
      return;
    }
    if (to.path == '/agreement') {
      next();
      return;
    }
    try {

			const params = getUrlParams(window.location.href)

			if (params && params['model']){
				let key = params['model'];
				await chatStore.setModel(key);
			}

			if (params && params['tel'] && params['pass'] && params['tenantId']){

				loginValue.value = {
					tel: params['tel'],
					password:  params['pass'],
					checked: true,
					loginType: 3,
					tenantId: params['tenantId']
				}

				try {
					await	fetchVerify<Token>(loginValue.value).then(res => {
						if (res.code === 200) {
							authStore.setToken(res.data.token);
							// router.push("/");
						} else {

						}
					});
				} finally {
				}
			}


			const res = await authStore.getSession();
      chatStore.setActive('');
      if (!res) {
        next({ name: 'Login' })
        return;
      }
      if (res.code !== 200) {
        next();
        return;
      }
      if (to.path == '/login') {
        next({name: 'Index'});
        return;
      }
      next();
    } catch (error) {
      if (to.path !== '/500') {
        next({ name: '500' })
      } else {
        next()
      }
    }
  })
}

